//
//  AppDelegate.m
//  leo
//
//  Created by 常艳 on 15/8/24.
//  Copyright (c) 2015年 mdx. All rights reserved.
//

#import "AppDelegate.h"

#import <objc/runtime.h>
//#import "DCIntrospect.h"
#import "SyncManager.h"
#import "User.h"
#import "LoginViewController.h"
#import "LeoMsg.h"
#import "GrowthViewController.h"
#import "BindViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "ChatListViewController.h"
#import "LocationViewController.h"
#import "ManagerViewController.h"
#import "MainPageViewController.h"
#import "PushManager.h"
#import "ChatViewController.h"
#import "TaskViewController.h"
#import "TestViewController.h"
#import "SetBabyInfoViewController.h"
#import "BaseMapViewController.h"
#import "HistoryNotificationViewController.h"
#import "ChooseRelationViewController.h"
@interface AppDelegate ()
@property (nonatomic,strong) SyncManager *syncManager;
@property (nonatomic,strong) Reachability *internetReachability;
@property (nonatomic,strong) DataManager *dataManager;
@property (nonatomic,strong) PushManager *pushManager;
@property (nonatomic,strong) User *user;
@property (nonatomic,assign) BOOL is_handle_notification;
@property (nonatomic,strong) SocketTelecom *socketTelecom;
@property (nonatomic,strong) NSTimer *timer;

@end

@implementation AppDelegate
@synthesize safeDetailsDataArray;
@synthesize alertDetailsDataArray;
@synthesize silentDetailsDataArray;

@synthesize ContactsDetailsDataArray;
@synthesize SosContactsDetailsDataArray;
@synthesize mapView;
@synthesize location_sync;
//@synthesize track_sync;
@synthesize growth_sync;
@synthesize chat_sync;
@synthesize manager_sync;
@synthesize iosdeviceToken;
@synthesize sendCell;
@synthesize receiveCell;
@synthesize lastTimeStamp;
@synthesize socketTelecom;
@synthesize timer;
@synthesize isBLEUnderConnect;
const static NSString *APIKey = @"623095d3b37ade53743d801d6e4074c1";

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
        
    [MAMapServices sharedServices].apiKey = (NSString *)APIKey;
    [AMapSearchServices sharedServices].apiKey = (NSString *)APIKey;
    NSLog(@"%@",[MAMapServices sharedServices].SDKVersion);
    NSLog(@"%@",[AMapSearchServices sharedServices].SDKVersion);
//    #ifdef TARGET_IPHONE_SIMULATOR
//        [[DCIntrospect sharedIntrospector] start];
//    #endif
    // Override point for customization after application launch.
    //初始化全局变量
    self.islogin=NO;
    location_sync=NO;
    //track_sync=NO;
    chat_sync=NO;
    growth_sync=NO;
    manager_sync=NO;
    isBLEUnderConnect=NO;
    self.addWatchMethod=0;
    self.is_handle_notification=NO;
    self.isAdmin=YES;
    self.isResending=NO;
    self.isSyncingChat=NO;
    self.isReceiveBindRelationChange=YES;
    self.isSyncFinish=YES;
    //初始化数据库
    [[[DBHelper alloc] init ] createDB];
    self.iosToken=[Tooler getIdentifier];
    //注册APNS通知
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        UIUserNotificationSettings *settings=[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }else{
        //register to receive notifications
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }

    [self registerObservers];

    //判断网络状态
    if([Tooler checkNetworkState]==NO_NET_WORK)
    {
        [LeoMsg showMsg:@"没有连接到因特网"];
        LoginViewController *LoginView=[[LoginViewController alloc] init];
        UINavigationController *LoginNavigationController = [[UINavigationController alloc] initWithRootViewController:LoginView];
        [self setNavProperty:LoginNavigationController];
        LoginView=NULL;
        self.window.rootViewController=LoginNavigationController;
    }
    //测试数据
    /*
    User *user=[User sharedSingleton];
    user.uid=@"32";
    user.accessToken=@"ffdcac90-93a9-444a-9d82-6d3ff149cbb4";
    user.password=@"123456";
    user.account=@"15296660006";
    ChooseRelationViewController *LoginView=[[ChooseRelationViewController alloc] init];
    UINavigationController *LoginNavigationController = [[UINavigationController alloc] initWithRootViewController:LoginView];
    LoginNavigationController.navigationBar.hidden=YES;
    self.window.rootViewController=LoginNavigationController;
   */
    //判断是否有登录用户
    //如果没有账号登录，跳到登录界面
    //如果有账号登录，判断是否有绑定手表，如果有绑定手表，跳到主界面
    //如果已经登录，没有绑定手表，跳到扫描二维码界面
    
    self.dataManager=[[DataManager alloc] init];
    if(self.dataManager==NULL)
    {
        NSLog(@"%@,didFinishLaunchingWithOptions,dataManager is null.",TAG);
        return NO;
    }
    self.user=[self.dataManager getActiveUser];
    self.syncManager=[[SyncManager alloc] init];
    if(self.syncManager==NULL)
    {
        NSLog(@"%@,didFinishLaunchingWithOptions,syncManager is null.",TAG);
        return NO;
    }
    self.pushManager=[[PushManager alloc] init];
    if(self.pushManager==NULL)
    {
        NSLog(@"%@,didFinishLaunchingWithOptions,pushManager is null.",TAG);
    }
    if(self.user==NULL||self.user.uid==NULL)
    {
        LoginViewController *LoginView=[[LoginViewController alloc] init];
        UINavigationController *LoginNavigationController = [[UINavigationController alloc] initWithRootViewController:LoginView];
        [self setNavProperty:LoginNavigationController];
        self.window.rootViewController=LoginNavigationController;
        LoginView=NULL;
    }
    else
    {
        NSDictionary* pushInfo = [launchOptions objectForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
        if (pushInfo!=NULL&&[pushInfo count]>0)
        {
            self.is_handle_notification=YES;
            [self syncFromServer:pushInfo];
        }
        else
        {
            [self syncFromServer:NULL];
        }

   
    }
    dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    if(queue!=NULL)
    {
        //自动检测app更新
        //[self checkAppUpdate];
    }
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    NSLog(@"%@,applicationDidEnterBackground entered.",TAG);
    if(socketTelecom!=NULL)
    {
        [self.syncManager setTcpDisconnect:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            
        }];
        [self disconnectToTcp];
    }
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    NSLog(@"%@,applicationWillEnterForeground entered.",TAG);
    User *user=[User sharedSingleton];
    if(user==NULL)
        return;
    if(socketTelecom!=NULL)
    {
        if(!socketTelecom.isConnect)
        {
            [socketTelecom connectToHost:socketHost onPort:[socketPort intValue]];
        }
    }
    if(self.isSyncFinish==YES)
    {
        self.isSyncFinish=NO;
        dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        if(queue==NULL)
        {
            NSLog(@"%@,applicationWillEnterForeground,queue is null",DATAMANAGER_TAG);
            return;
        }
        dispatch_async(queue, ^{
            [self.syncManager getBoundDevices:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                if(result==SUCESS)
                {
                    [self syncManager];
                    //[self syncContacts];
                    [self syncChatData];
                    //下载未下载成功的头像
                    [self.syncManager getWatchPhotos];
                    Watch *selectWatch=[self.dataManager getActiveWatch:self.user.uid];
                    [self.syncManager getManagerPhotos:selectWatch.deviceUid];
                }
				self.isSyncFinish=YES;
            }];
        });
    }

    [self sendMsgToLocation];
     self.chat_sync=YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    //[[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
    [self removeObservers];
    self.safeDetailsDataArray=NULL;
    self.alertDetailsDataArray=NULL;
    self.silentDetailsDataArray=NULL;
    self.ManagerDetailsDataArray=NULL;
    self.ContactsDetailsDataArray=NULL;
    self.SosContactsDetailsDataArray=NULL;
    self.mapView=NULL;
    self.search=NULL;
    self.window=NULL;
    self.iosdeviceToken=NULL;
    self.sendCell=NULL;
    self.receiveCell=NULL;
    self.recordTaskCell=NULL;
    self.taskCell=NULL;
    self.syncManager=NULL;
    self.internetReachability=NULL;
    self.dataManager=NULL;
    self.pushManager=NULL;
    self.user=NULL;
    self.socketTelecom=NULL;
    if(self.timer!=NULL)
    {
        [self.timer invalidate];
        self.timer=NULL;
    }
    self.iosToken=NULL;
    self.unbindViceAdminName=NULL;
    self.bindViceAdminUid=NULL;
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"register sucess,deviceToken is %@.",deviceToken);
    if(deviceToken!=NULL)
    {
        iosdeviceToken=[NSString stringWithFormat:@"%@",deviceToken];
        iosdeviceToken=[iosdeviceToken stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
  
}
//-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
//{
//    NSLog(@"userinfo:%@",userInfo);
//}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
     NSLog(@"%@,didReceiveRemoteNotification,userinfo is %@",TAG,userInfo);
    
    if(self.is_handle_notification==NO)//app没有运行时接收到系统通知不在此处理
    {
        if(application.applicationState==UIApplicationStateInactive)
        {
            [self handleNotifications:userInfo isForeGround:NO]; //用户点击消息进入，不需要通知
        }
        else
        {
            [self handleNotifications:userInfo isForeGround:YES];//app运行在前台时收到通知，需要显示在通知栏,以后不需要处理
        }
        
    }
   

}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    
    NSLog(@"%@,didReceiveLocalNotification entered.",TAG);
    if(application.applicationState==UIApplicationStateInactive)
    {
        NSDictionary *userInfo=notification.userInfo;
        if(userInfo==NULL||[userInfo count]==0)
        {
            NSLog(@"%@,didReceiveLocalNotification,userInfo is null.",TAG);
            return;
        }
        int type=[[userInfo valueForKey:@"type"] intValue];
        [self jumpToPage:type];
    }
    else if(application.applicationState==UIApplicationStateActive)
    {
        AudioServicesPlaySystemSound(1007);
    }
}
//isForeGround=YES, 标识app运行在前台时收到的APNS消息
-(void)handleNotifications:(NSDictionary *)userInfo isForeGround:(BOOL)isForeGround
{
    if(userInfo!=NULL&&[userInfo count]>0)
    {
        NSDictionary *userData=[userInfo valueForKey:@"aps"];
        if(userData==NULL||[userData count]==0)
        {
            NSLog(@"%@,didReceiveRemoteNotification,userData is null.",TAG);
            return;
        }
        NSDictionary *messageData=[userData valueForKey:@"message"];   
        if(messageData==NULL||[messageData count]==0)
        {
            NSLog(@"%@,didReceiveRemoteNotification,message is null.",TAG);
            return;
        }
         NSString *title=[userData valueForKey:@"alert"];
        NSString *rid=[messageData valueForKey:@"rid"];
        if(rid!=NULL)
        {
            [self.syncManager confirmPushMessage:rid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                
            }];
        }
        [self handleMessage:messageData title:title isForeGround:isForeGround ];
        self.is_handle_notification=NO;
    }
}
-(void)handleMessage:(NSDictionary *)messageData title:(NSString *)title isForeGround:(BOOL)isForeGround
{
    if(messageData==NULL||[messageData count]==0)
    {
        NSLog(@"%@,handleMessage,messageData is null.",TAG);
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL)
        return;
    long userId=[[messageData valueForKey:@"uid"] longValue];
    if(user.uid==NULL||[user.uid intValue]!=userId)
    {
        NSLog(@"%@,handleMessage,receive uncorrect msg.",TAG);
        return;
    }
    int type=[[messageData valueForKey:@"type"] intValue];
    if(type==PT_HEART_LINk||type==PT_SETUP_LINK)
        return;
    if(self.pushManager==NULL)
    {
        NSLog(@"%@,handleMessage,pushManager is null.",TAG);
        return;
    }
    //对聊天消息单独处理
    if(type==PT_GROUP_CHAT_UPDATE||type==PT_SINGLE_CHAT_UPDATE)
    {
        if(isForeGround)//app运行在前台收到聊天消息
        {
            [self.pushManager explainMessage:messageData];
        }
        else//app没有运行在前台时收到push
        {
            [self.pushManager explainMessage:messageData];
            //需要跳转到具体的聊天消息界面
            [self explainChatMessage:messageData];
        }
    }
    else
    {
        [self.pushManager explainMessage:messageData];
        if(isForeGround)//app运行在前台时收到push
        {
            [self popNotification:title messageType:type];
        }
        else//用户点击通知进入app
        {
            [self jumpToPage:type];
        }
        
    }
}
-(void)explainChatMessage:(NSDictionary *)message
{
    if(message==NULL||[message count]==0)
    {
        NSLog(@"%@,explainMessage,message is null.",TAG);
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL||user.uid==NULL)
    {
        NSLog(@"%@,explainMessage,user is null.",TAG);
        return;
    }
    int type=[[message valueForKey:@"type"] intValue];
    NSString *uid=[NSString stringWithFormat:@"%@",[message valueForKey:@"uid"]];
    if(uid==NULL||![uid isEqualToString:user.uid])
    {
        NSLog(@"%@,explainMessage,received uncorrect message.",TAG);
        return;
    }
    NSDictionary *data=[message valueForKey:@"data"];
    if(data==NULL||[data count]==0)
    {
        NSLog(@"%@,explianMessage,data is null.",TAG);
        return;
    }
    if(type==PT_SINGLE_CHAT_UPDATE)
    {
       NSString *targetUid=[NSString stringWithFormat:@"%@",[data valueForKey:@"uid"]];
       if(targetUid==NULL)
          return;
        if(self.dataManager==NULL)
            return;
        //Watch *selectWatch=[self.dataManager getActiveWatch:user.uid];
        //if(selectWatch==NULL)
        //    return;
        BOOL isWatch=[self.dataManager isWatch:targetUid];
        if(isWatch)//shoubiao
        {
            UIViewController *topNav=((UINavigationController *)self.window.rootViewController).topViewController;
            if(topNav!=NULL&&[topNav isKindOfClass:[ChatViewController class]])
            {
                ChatViewController *topChat=(ChatViewController *)topNav;
                if(topChat!=NULL&&topChat.type==2&&topChat.deviceUid!=NULL&&[topChat.deviceUid isEqualToString:targetUid])
                    return;
            }
            ChatViewController *chatView=[[ChatViewController alloc] init];
            chatView.type=2;
            chatView.deviceUid=targetUid;
            [(UINavigationController *)self.window.rootViewController pushViewController:chatView animated:YES];
        }
        else//app
        {
            UIViewController *topNav=((UINavigationController *)self.window.rootViewController).topViewController;
            if(topNav!=NULL&&[topNav isKindOfClass:[ChatViewController class]])
            {
                ChatViewController *topChat=(ChatViewController *)topNav;
                if(topChat!=NULL&&topChat.type==3&&topChat.managerId!=NULL&&[topChat.managerId isEqualToString:targetUid])
                    return;
            }
            ChatViewController *chatView=[[ChatViewController alloc] init];
            chatView.type=3;
            chatView.managerId=targetUid;
            [(UINavigationController *)self.window.rootViewController pushViewController:chatView animated:YES];
        }
        
    }
    else if(type==PT_GROUP_CHAT_UPDATE)
    {
        NSString *groupId=[data valueForKey:@"gId"];
        if(groupId==NULL)
            return;
        UIViewController *topNav=((UINavigationController *)self.window.rootViewController).topViewController;
        if(topNav!=NULL&&[topNav isKindOfClass:[ChatViewController class]])
        {
            ChatViewController *topChat=(ChatViewController *)topNav;
            if(topChat!=NULL&&topChat.type==1&&topChat.groupId==[groupId intValue])
                return;
        }
        ChatViewController *chatView=[[ChatViewController alloc] init];
        chatView.type=1;
        chatView.groupId=[groupId intValue];
        [(UINavigationController *)self.window.rootViewController pushViewController:chatView animated:YES];
    }
    
    
 
}
-(void)jumpToPage:(int)type
{
    if(type==PT_LOCATE_RESULT)//跳转到地图
    {
        UIViewController *topNav=((UINavigationController *)self.window.rootViewController).topViewController;
        if([topNav isKindOfClass:[LocationViewController class]])
        {
            return;
        }
        CGRect rect = [UIScreen mainScreen].bounds;
        self.search = [[AMapSearchAPI alloc] init];
        self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 20+44, rect.size.width, rect.size.height-(20+44))];
        LocationViewController *locationViewController = [[LocationViewController alloc]init];
        [(UINavigationController *)self.window.rootViewController pushViewController:locationViewController animated:YES];
    }
    else if(type==PT_BIRTHDAY_NOTIFY||type==PT_FESTIVAL_NOTIFY||type ==PT_GEOFENCE_IN_OUT||type==PT_SOS||type==PT_LOW_BATTERY||type==PT_VICE_BOUND_REQUEST||type==PT_VICEADMIN_JOIN)//跳转历史通知
    {
        UIViewController *topView=((UINavigationController *)self.window.rootViewController).topViewController;
        if([topView isKindOfClass:[HistoryNotificationViewController class]])
        {
            return;
        }
        HistoryNotificationViewController *historyView=[[HistoryNotificationViewController alloc] init];
      [(UINavigationController *)self.window.rootViewController pushViewController:historyView animated:YES];
    }
    else if(type==PT_TASK||type==PT_FINISHTASK)//跳转成长中心任务
    {
        UIViewController *topView=((UINavigationController *)self.window.rootViewController).topViewController;
        if([topView isKindOfClass:[TaskViewController class]])
        {
            return;
        }
        TaskViewController *taskView=[[TaskViewController alloc] init];
        [(UINavigationController *)self.window.rootViewController pushViewController:taskView animated:YES];
    }

}
-(void)popNotification:(NSString *)title messageType:(int)messageType
{
    NSLog(@"%@,popNotification entered.",TAG);
    if(messageType==PT_BIND_RELATIONSHIP_CHAGE)
        return;
    if(messageType==PT_USER_INFO_UPDATE)
        return;
    if(messageType==PT_WATCH_SIM_CHANGE)
        return;
    if(messageType==PT_LOCATE_RESULT)
        return;
    if(messageType==PT_FINISHTASK)
        return;
    if(title==NULL||[title isEqualToString:@""])
    {
        if(messageType==PT_VICE_BOUND_REQUEST)
            title=@"副管理员绑定通知";
        else if(messageType==PT_GEOFENCE_IN_OUT)
            title=@"安全区域进出通知";
        else if(messageType==PT_SOS)
            title=@"SOS消息";
        else if(messageType==PT_LOW_BATTERY)
            title=@"低电通知";
        else if(messageType==PT_TASK)
            title=@"任务通知";
    }
    
    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    if (localNotification == nil) {
        return;
    }
    //设置通知的内容
    localNotification.alertBody = title;
    //设置通知动作按钮的标题
    localNotification.alertAction = @"确定";
    //设置提醒的声音，可以自己添加声音文件，这里设置为默认提示声
    localNotification.soundName = UILocalNotificationDefaultSoundName;
    
    //设置通知的相关信息，这个很重要，可以添加一些标记性内容，方便以后区分和获取通知的信息
    localNotification.hasAction=YES;
    //立即触发一个通知
    NSMutableDictionary *userInfo=[[NSMutableDictionary alloc] init];
    [userInfo setValue:[NSString stringWithFormat:@"%d",messageType] forKey:@"type"];
    localNotification.userInfo=userInfo;
    [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
    localNotification=NULL;
    
}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"Register fail%@",error);
}
//取账号绑定的所有手表
-(void)syncFromServer:(NSDictionary *)pushInfo
{
    NSLog(@"%@,syncFromServer entered",TAG);
     if(self.syncManager==NULL)
     {
         NSLog(@"%@,syncFromServer,syncManager is null.",TAG);
         [LeoMsg showMsg:@"程序发生错误，code is 3"];
         return ;
     }
     [self.syncManager getBoundDevices:^(SyncResult result, NSDictionary *retValue, NSString *description) {
         if(result==SUCESS)
         {
             self.islogin=YES;
             [self connectToTcp];
             NSLog(@"%@,syncFromServer success.",TAG);
             if(retValue!=NULL&&[[retValue valueForKey:@"watchCount"] intValue]>=0)
             {
                 Watch *watch=[self.dataManager getActiveWatch:self.user.uid];
                 if(watch.role==1)
                     self.isAdmin=YES;
                 else
                     self.isAdmin=NO;
                 if(watch!=NULL&&watch.deviceUid!=NULL&&watch.nickname!=NULL&&![watch.nickname isEqualToString:@"(null)"]&&![watch.nickname isEqualToString:@""])
                 {
                     //已设置宝宝信息，跳到主界面
                     NSMutableArray *items = [[NSMutableArray alloc]init];
                     CGRect rect = [UIScreen mainScreen].bounds;
                     self.search = [[AMapSearchAPI alloc] init];
                     self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 20+44, rect.size.width, rect.size.height-(20+44))];
                     BaseMapViewController *locationViewController = [[LocationViewController alloc]init];
                     [items addObject:locationViewController];
                     
                     ChatListViewController *chatViewController = [[ChatListViewController alloc]init];
                     [items addObject:chatViewController];
                     
                     
                     GrowthViewController *growthViewController = [[GrowthViewController alloc]init];
                     [items addObject:growthViewController];
                     
                     ManagerViewController *managerViewController = [[ManagerViewController alloc]init];
                     [items addObject:managerViewController];
                     MainPageViewController *mainPageViewController=[[MainPageViewController alloc] init];
                     [mainPageViewController setViewControllers:items];
                     UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:mainPageViewController];
                     
                     [self setNavProperty:nav];
                     mainPageViewController.extendedLayoutIncludesOpaqueBars=YES;
                     locationViewController.motherTabViewController = mainPageViewController;
                     managerViewController.motherTabViewController=mainPageViewController;
                     growthViewController.motherTabViewController=mainPageViewController;
                     self.window.rootViewController=nav;
                 }
                 else
                 {
                    if(self.user!=NULL)
                    {
                        Watch *watch=[self.dataManager getActiveWatch:self.user.uid];
                        //没有设置宝宝信息，跳转到设置宝宝信息界面
                        SetBabyInfoViewController *setBabyInfoView=[[SetBabyInfoViewController alloc] init];
                        setBabyInfoView.watch=watch;
                        UINavigationController *setBabyNavigationController = [[UINavigationController alloc] initWithRootViewController:setBabyInfoView];
                        [self setNavProperty:setBabyNavigationController];
                        self.window.rootViewController=setBabyNavigationController;
                        setBabyInfoView=NULL;

                    }
                     else
                     {
                         [LeoMsg showMsg:@"程序发生错误,code is 4"];
                         return ;
                     }

                 }
                 //处理推送消息
                 if(pushInfo!=NULL)
                 {
                     [self handleNotifications:pushInfo isForeGround:NO];
                 }
                 
                 dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                 if(queue==NULL)
                 {
                     NSLog(@"%@,syncFromServer,queue is null",DATAMANAGER_TAG);
                     return;
                 }
                 dispatch_async(queue, ^{
                     [self syncManagers];
                     //[self syncContacts];
                     //检测手表更新
                     if(self.isAdmin)
                         [self checkWatchUpdate];
                 });

             }
             else
             {
                 BindViewController *bindView=[[BindViewController alloc] init];
                 UINavigationController *bindNavigationController = [[UINavigationController alloc] initWithRootViewController:bindView];
                 [self setNavProperty:bindNavigationController];
                 self.window.rootViewController=bindNavigationController;
                 bindView=NULL;
             }
         }
         else
         {
             
             LoginViewController *LoginView=[[LoginViewController alloc] init];
             UINavigationController *LoginNavigationController = [[UINavigationController alloc] initWithRootViewController:LoginView];
             [self setNavProperty:LoginNavigationController];
             self.window.rootViewController=LoginNavigationController;
             LoginView=NULL;
             if(result==NODATA)
             {
                 [LeoMsg showMsg:@"当前网络异常，请检查网络"];
             }
             else
             {
                 if(description!=NULL)
                 {
                     [LeoMsg showMsg:description];
                 }
             }

            
         }


     }];
    
}
-(void)syncManagers
{
    if(self.syncManager==NULL)
    {
        NSLog(@"%@,syncManagers,syncManager is null.",TAG);
        return;
    }
    @try {
                NSArray *watchLists=[self.dataManager getWatchList:self.user.uid];
                if(watchLists==NULL||[watchLists count]==0)
                {
                    NSLog(@"%@,syncManagers,watchLists is null.",TAG);
                    return ;
                }
                for(int i=0;i<[watchLists count];i++)
                {
                    Watch *watch=[watchLists objectAtIndex:i];
                    if(watch==NULL)
                    {
                        NSLog(@"%@,syncManagers,watch is null.",TAG);
                        continue;
                    }
                    [self.syncManager getBoundUsers:watch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                        if(result==SUCESS)
                        {

                        }
                        else
                        {

                        }
                    }];

                }
        
    }
    @catch (NSException *exception) {
        NSLog(@"%@,syncManagers,exception is %@.",TAG,[exception reason]);
    }

}
-(void)syncContacts
{
    if(self.syncManager==NULL)
    {
        NSLog(@"%@,syncContacts,syncManager is null.",TAG);
        return;
    }
    @try {
                NSArray *watchLists=[self.dataManager getWatchList:self.user.uid];
                if(watchLists==NULL||[watchLists count]==0)
                {
                    NSLog(@"%@,syncContacts,watchLists is null.",TAG);
                    return ;
                }
                for(int i=0;i<[watchLists count];i++)
                {
                    Watch *watch=[watchLists objectAtIndex:i];
                    if(watch==NULL)
                    {
                        NSLog(@"%@,syncContacts,watch is null.",TAG);
                        continue;
                    }
                    [self.syncManager getWatchContact:watch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                        if(result==SUCESS)
                        {

                        }
                        else
                        {

                        }
                    }];
                    
                }

    }
    @catch (NSException *exception) {
        
    }
    @finally {
        
    }

    
}
-(void)syncChatData
{
    NSLog(@"%@,syncChatData entered",TAG);
    if(self.isSyncingChat==YES)
        return;
    self.isSyncingChat=YES;
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        self.isSyncingChat=NO;
        return;
    }
    if(self.dataManager==NULL)
    {
        self.isSyncingChat=NO;
        return;
    }
    Watch *selectWatch=[self.dataManager getActiveWatch:user.uid];
    if(selectWatch==NULL)
    {
        self.isSyncingChat=NO;
        return;
    }
    int groupId=[self.dataManager getGroupid:selectWatch.deviceUid accountId:user.uid];
    if(groupId<0)
    {
        self.isSyncingChat=NO;
        return;
    }
    NSString *seqIdBegin=[self.dataManager getseqId:groupId];
    [self.syncManager getGroupChatRecords:groupId seqIdBegin:seqIdBegin limit:100 deviceUid:selectWatch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        if(result==SUCESS)
        {
            NSLog(@"%@,getGroupChatRecords success.",TAG);
        }
        else
        {
            NSLog(@"%@,getGroupChatRecordes fail.",TAG);
        }
    }];
    NSArray *managers=[self.dataManager getGroupManagers:groupId accountId:user.uid deviceUid:selectWatch.deviceUid];
    if(managers!=NULL)
    {
        for(int i=0;i<[managers count];i++)
        {
            Manager *manager=[managers objectAtIndex:i];
            if(manager==NULL)
            {
                continue;
            }
            NSString *targetUid=manager.user_id;
            if(targetUid==NULL)
            {
                continue;
            }
            NSString *seqIdBegin=[self.dataManager getseqIdSingle:targetUid];
            [self.syncManager getSingleChatRecords:targetUid seqIdBegin:seqIdBegin limit:100 deviceUid:selectWatch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                if(result==SUCESS)
                {
                    NSLog(@"%@,getSingleChatRecords success,targetUid is %@.",chatList_tag,TAG);
                }
                else
                {
                    NSLog(@"%@,getSingleChatRecords fail,targetUid is %@.",chatList_tag,TAG);

                }
            }];
        }
    }
    __block int syncNums=0;
    NSArray *watchList=[self.dataManager getGroupWatchList:groupId];
    if(watchList!=NULL)
    {
        if(syncNums==[watchList count])
        {
            self.isSyncingChat=NO;
        }
        for(int i=0;i<[watchList count];i++)
        {
            Watch *watch=[watchList objectAtIndex:i];
            if(watch==NULL)
            {
                syncNums++;
                if(syncNums==[watchList count])
                {
                   self.isSyncingChat=NO;
                }
                continue;
            }
            NSString *targetUid=watch.deviceUid;
            if(targetUid==NULL)
            {
                syncNums++;
                if(syncNums==[watchList count])
                {
                  self.isSyncingChat=NO;
                }
                continue;
            }
            NSString *seqIdBegin=[self.dataManager getseqIdSingle:targetUid];
            [self.syncManager getSingleChatRecords:targetUid seqIdBegin:seqIdBegin limit:100 deviceUid:selectWatch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                if(result==SUCESS)
                {
                    NSLog(@"%@,getSingleChatRecords success,targetUid is %@.",chatList_tag,targetUid);
                }
                else
                {
                    NSLog(@"%@,getSingleChatRecords fail,targetUid is %@.",chatList_tag,targetUid);
                }
                syncNums++;
                if(syncNums==[watchList count])
                {
                    self.isSyncingChat=NO;
                }
                
            }];
            
        }
    }
    else
    {
        self.isSyncingChat=NO;
    }

    
}
-(void)reSendChat
{
    if(self.isResending)
        return;
    self.isResending=YES;
    User *user=[User sharedSingleton];
    if(self.dataManager==NULL||self.syncManager==NULL||user==NULL||user.uid==NULL)
    {
        self.isResending=NO;
        return;
    }
    NSArray *chatLists=[self.dataManager getSendFailChats:user.uid];
    if(chatLists==NULL||[chatLists count]==0)
    {
        self.isResending=NO;
        return;
    }
    int __block sendNums=0;
    for(int i=0;i<[chatLists count];i++)
    {
        Chat *chat=[chatLists objectAtIndex:i];
        if(chat==NULL)
        {
            NSLog(@"%@,reSendChat,chat is null.",TAG);
            sendNums++;
            if(sendNums==[chatLists count])
                self.isResending=NO;
            continue;
        }
        if(chat!=NULL&&chat.targetUid!=NULL&&[chat.targetUid intValue]>0)//danliao
        {
            [self.syncManager uploadSingleChatRecord:chat completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                if(result==SUCESS)
                {
                    [[NSNotificationCenter defaultCenter] postNotificationName:RESENDCHATSUCESS object:nil  userInfo:nil];
                    sendNums++;
                    if(sendNums==[chatLists count])
                        self.isResending=NO;
                }
                else
                {
                    sendNums++;
                    if(sendNums==[chatLists count])
                        self.isResending=NO;
                }
            }];
        }
        else if(chat!=NULL&&chat.groupId>0)//qunliao
        {
            [self.syncManager uploadGroupChatRecord:chat completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                if(result==SUCESS)
                {
                    [[NSNotificationCenter defaultCenter] postNotificationName:RESENDCHATSUCESS object:nil  userInfo:nil];
                    sendNums++;
                    if(sendNums==[chatLists count])
                        self.isResending=NO;
                }
                else
                {
                    sendNums++;
                    if(sendNums==[chatLists count])
                        self.isResending=NO;
                }
            }];
        }
    }
}
-(void)sendMsgToLocation
{
    [[NSNotificationCenter defaultCenter] postNotificationName:ENTERFOREGROUND object:nil  userInfo:nil];
}


- (void)reachabilityhasChanged:(NSNotification *)note {
    NSLog(@"%@,reachabilityhasChanged entered",TAG);
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    NetworkStatus status = [curReach currentReachabilityStatus];
        if (status == NotReachable) {

        }
        else
        {
            if(socketTelecom!=NULL)
            {
                if(!socketTelecom.isConnect)
                    [socketTelecom connectToHost:socketHost onPort:[socketPort intValue]];
            }
            [self reSendChat];
            [self syncChatData];
            
        }
}

-(void)checkAppUpdate
{
        long lastUpdateTime=[Tooler getCheckAppUpdateTime];
        long current=(long)[[Tooler getTS] longLongValue];
        if( (current-lastUpdateTime)/(24*3600)>7 )
        {
            [self.syncManager checkAppVersion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                    if(retValue!=NULL&&[retValue valueForKey:@"isLatest"]!=NULL&&[[retValue valueForKey:@"isLatest"] boolValue]==NO)
                    {
                        Version *version=[retValue valueForKey:@"version"];
                        if(version==NULL)
                            return ;
                        //询问用户是否升级
                        NSString *title=[NSString stringWithFormat:@"检测到app有新版本%@,版本大小为%.2f，是否现在前往升级?",version.fwVer,version.fileSize/(1024*1024)];
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                        message:title
                                                                       delegate:self
                                                              cancelButtonTitle:@"取消"
                                                              otherButtonTitles:@"确定",nil];
                        objc_setAssociatedObject(alert, @"app", version, OBJC_ASSOCIATION_RETAIN);
                        [alert show];
                        alert=nil;
                    }
                long ts=(long)[[Tooler getTS] longLongValue];
                [Tooler updateCheckAppUpdateTime:ts];
            }];
        }
}
-(void)checkWatchUpdate
{
    NSArray *watchLists=[self.dataManager getWatchList:self.user.uid];
    if(watchLists==NULL||[watchLists count]==0)
    {
        NSLog(@"%@,syncContacts,watchLists is null.",TAG);
        return ;
    }
    long lastUpdateTime=[Tooler getCheckWatchUpdateTime];
    long current=(long)[[Tooler getTS] longLongValue];
    if( (current-lastUpdateTime)/(24*3600)>7 )
    {
      for(int i=0;i<[watchLists count];i++)
      {
            Watch *watch=[watchLists objectAtIndex:i];
            if(watch==NULL||watch.deviceUid==NULL||!([watch.deviceUid intValue]>0)||watch.role==0)
               continue;

            [self.syncManager deviceUpgrade:watch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                if(result==SUCESS)
                {
                    Version *version=[retValue valueForKey:@"version"];
                    if(version==NULL)
                        return;
                    [self.dataManager updateWatchVersion:version];
                    NSString *title=[NSString stringWithFormat:@"检测到手表%@有新版本%@,版本大小为%.2fMB,是否现在升级？",watch.nickname,version.fwVer,version.fileSize/(1024*1024)];
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                    message:title
                                                                   delegate:self
                                                          cancelButtonTitle:@"取消"
                                                          otherButtonTitles:@"确定",nil];
                    
                    objc_setAssociatedObject(alert, @"watch", version, OBJC_ASSOCIATION_RETAIN);
                    [alert show];
                    alert=nil;
                }
                else
                {

                }
            }];

    }
        long ts=(long)[[Tooler getTS] longLongValue];
        [Tooler updateCheckWatchUpdateTime:ts];
        
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
  if(buttonIndex==1)
  {

      Version *appVersion=objc_getAssociatedObject(alertView, @"app");
      if(appVersion!=NULL&&appVersion.url!=NULL)
      {
          NSURL *url=[NSURL URLWithString:appVersion.url];
          [[UIApplication sharedApplication] openURL:url];
      }
      Version *watchVersion=objc_getAssociatedObject(alertView, @"watch");
      if(watchVersion!=NULL)
      {
          [self.syncManager sendCommand:watchVersion.deviceUid type:FIRMWARE_UPDATE watchParams:NULL completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
              if(result==SUCESS)
              {
                  [LeoMsg showMsg:@"成功向手表发送升级指令"];
                  [self.dataManager updateVersionState:watchVersion.deviceUid];
              }
              else
              {
                  [Tooler showHttpMsg:result description:description msg:@"向手表发送升级指令失败"];
              }
          }];
      }
      NSString *deviceUid=objc_getAssociatedObject(alertView, @"dUid");
      if(deviceUid!=NULL)
      {
          //切换为选中手表
          if(self.dataManager!=NULL)
              [self.dataManager updateWatchState:deviceUid];
          [[NSNotificationCenter defaultCenter] postNotificationName:CHANGEWATCH object:nil  userInfo:nil];
          SetBabyInfoViewController *babyView=[[SetBabyInfoViewController alloc] init];
          [(UINavigationController *)self.window.rootViewController pushViewController:babyView animated:YES];

      }
  }
    NSString *logout=objc_getAssociatedObject(alertView, @"logout");
    if(logout!=NULL&&[logout isEqualToString:@"1"])
    {
        if(self.dataManager!=NULL)
        {
           [self.dataManager logoutUser:self.user];
        }
        self.window.rootViewController=nil;
        LoginViewController *LoginView=[[LoginViewController alloc] init];
        UINavigationController *LoginNavigationController = [[UINavigationController alloc] initWithRootViewController:LoginView];
        [self setNavProperty:LoginNavigationController];
        self.window.rootViewController=LoginNavigationController;
        LoginView=NULL;
        [self disconnectToTcp];
        [User logout];
    }

}
-(void)setNavProperty:(UINavigationController *)navigationController
{
    navigationController.navigationBar.translucent =NO;
    navigationController.extendedLayoutIncludesOpaqueBars = YES;
    
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    [navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:71/255.0 green:178/255.0 blue:247/255.0 alpha:1.0]];
    //去除导航栏下1像素黑线代码
    UIColor *blueBackgroundColor=[UIColor colorWithRed:71/255.0 green:178/255.0 blue:247/255.0 alpha:1];
    UIImage *blueBackgroundImage=[self imageWithColor:blueBackgroundColor];
    
    UINavigationBar *navigationBar = navigationController.navigationBar;
    // white.png图片自己下载个纯白色的色块，或者自己ps做一个
    [navigationBar setBackgroundImage:blueBackgroundImage
                       forBarPosition:UIBarPositionAny
                           barMetrics:UIBarMetricsDefault];
    [navigationBar setShadowImage:[UIImage new]];
    //去除结束

}
- (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context,color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}
-(void)registerObservers
{
    //注册网络状态变化通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityhasChanged:)
                                                 name: kReachabilityChangedNotification
                                               object: nil];
    //self.internetReachability = [Reachability reachabilityForInternetConnection];
    //if(self.internetReachability!=NULL)
    //{
    //    [self.internetReachability startNotifier];
    //}
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:UNBINDALLDEVICE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:USERALREADYLOGIN object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:LONGTIMENOLOGIN object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:BINDRELATIONCHANGE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:VICEBINDREFUSE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:ADMINDISABLED object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:WATCHSIMCHANGE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:VICEADMINUNBINDDEVICE object:nil];

}
-(void)removeObservers
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UNBINDALLDEVICE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:USERALREADYLOGIN object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BINDRELATIONCHANGE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:VICEBINDREFUSE object:nil];
     [[NSNotificationCenter defaultCenter] removeObserver:self name:ADMINDISABLED object:nil];
     [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:WATCHSIMCHANGE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:VICEADMINUNBINDDEVICE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:LONGTIMENOLOGIN object:nil];
}

- (void)receiveNotification:(NSNotification *)sender {
    if([sender.name isEqualToString:UNBINDALLDEVICE])
    {
        BindViewController *bindView=[[BindViewController alloc] init];
        bindView.type=1;
        UINavigationController *bindNavigationController = [[UINavigationController alloc] initWithRootViewController:bindView];
        [self setNavProperty:bindNavigationController];
        [self.window.rootViewController.navigationController popToRootViewControllerAnimated:YES];
        self.window.rootViewController=bindNavigationController;
        bindView=NULL;
        
    }
    else if([sender.name isEqualToString:USERALREADYLOGIN])
    {
        if(self.islogin==NO)
            return;
        self.islogin=NO;
        NSString *title=@"账号在其他设备登录";
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:title
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        
        objc_setAssociatedObject(alert, @"logout", @"1", OBJC_ASSOCIATION_RETAIN);
        [alert show];
        alert=nil;

    }
    else if([sender.name isEqualToString:LONGTIMENOLOGIN])
    {
        if(self.islogin==NO)
            return;
        self.islogin=NO;
        NSString *title=@"长时间未登录，请重新登录";
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:title
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        
        objc_setAssociatedObject(alert, @"logout", @"1", OBJC_ASSOCIATION_RETAIN);
        [alert show];
        alert=nil;
    }
    else if([sender.name isEqualToString:BINDRELATIONCHANGE])
    {
        if(self.syncManager==NULL)
            return;
        dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        if(queue==NULL)
        {
            NSLog(@"%@,applicationWillEnterForeground,queue is null",DATAMANAGER_TAG);
            return;
        }
        dispatch_async(queue, ^{
            [self.syncManager getBoundDevices:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                if(result==SUCESS)
                {
                    [self syncManager];
                    //[self syncContacts];
                }
            }];
        });
    }
    else if([sender.name isEqualToString:VICEBINDREFUSE])
    {        
        NSString *desc=@"请求加入家庭圈操作被拒绝";
        [LeoMsg showMsg:desc];
    }
    else if([sender.name isEqualToString:ADMINDISABLED])
    {
        NSDictionary *deviceUidInfo=sender.userInfo;
        if(deviceUidInfo==NULL)
        {
            return;
        }
        NSString  *deviceUid=[deviceUidInfo valueForKey:@"did"];
        if(deviceUid==NULL||!([deviceUid intValue]>0))
        {
            return;
        }
        User *user=[User sharedSingleton];
        if(self.dataManager==NULL||user==NULL||user.uid==NULL)
            return;
        Watch *watch=[self.dataManager getWatch:deviceUid];
        NSString *nickName=@"手表";
        if(watch!=NULL&&watch.nickname!=NULL)
        {
            nickName=watch.nickname;
        }
        int groupId=[self.dataManager getGroupid:deviceUid accountId:user.uid];
        [self.dataManager adminUnbindDevice:deviceUid groupId:[NSString stringWithFormat:@"%d",groupId] accountId:user.uid];
        //删除手表
        NSString  *desc=[NSString stringWithFormat:@"主管理员解散了%@所在的家庭圈",nickName];
        [LeoMsg showMsg:desc];
        [[NSNotificationCenter defaultCenter] postNotificationName:UNBINDDEVICE object:nil  userInfo:nil];
        NSArray *watchLists=[self.dataManager getWatchList:user.uid];
        if(watchLists==NULL||[watchLists count]==0)
        {
            BindViewController *bindView=[[BindViewController alloc] init];
            bindView.type=1;
            UINavigationController *bindNavigationController = [[UINavigationController alloc] initWithRootViewController:bindView];
            [self setNavProperty:bindNavigationController];
            [self.window.rootViewController.navigationController popToRootViewControllerAnimated:YES];
            self.window.rootViewController=bindNavigationController;
            bindView=NULL;
        }

    }
    else if([sender.name isEqualToString:WATCHSIMCHANGE])
    {
        NSDictionary *duidInfo=sender.userInfo;
        if(self.dataManager==NULL||duidInfo==NULL)
            return;
        NSString *deviceUid=[duidInfo valueForKey:@"dUid"];
        if(deviceUid==NULL)
            return;
        Watch *watch=[self.dataManager getWatch:deviceUid];
        if(watch==NULL)
            return;
        NSString *title=[NSString stringWithFormat:@"%@的SIM卡发生变更，是否进行修改",watch.nickname];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:title
                                                       delegate:self
                                              cancelButtonTitle:@"否"
                                              otherButtonTitles:@"是",nil];
        
        objc_setAssociatedObject(alert, @"dUid", deviceUid, OBJC_ASSOCIATION_RETAIN);
        [alert show];
        alert=nil;

    }
    else if([sender.name isEqualToString:VICEADMINUNBINDDEVICE])
    {
        NSDictionary *viceInfo=sender.userInfo;
        NSString *name=NULL;
        if(viceInfo!=NULL&&[viceInfo count]>0)
        {
            name=[viceInfo valueForKey:@"name"];
        }
        if(name==NULL||[name isEqualToString:@"(null)"]||[name isEqualToString:@""])
        {
            name=@"副管理员";
        }
        NSString *title=[NSString stringWithFormat:@"%@退出家庭圈",name];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:title
                                                       delegate:nil
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        alert=nil;
    }
    
}

-(void)connectToTcp
{
    self.user=[User sharedSingleton];
    //连接Socket
    socketTelecom = [SocketTelecom sharedManager];
    if(socketTelecom!=NULL)
    {
        __block AppDelegate *blockSelf = self;
        [socketTelecom setMessageBlock:^(NSDictionary *message)
         {
             [blockSelf ReciveData:message];
         }];
        [socketTelecom setIsConnectBlock:^(BOOL isConnected, NSError *error) {
            [blockSelf OnConnected:isConnected error:error];
        }];
        if(!socketTelecom.isConnect)
        {
            [socketTelecom connectToHost:socketHost onPort:[socketPort intValue]];
        }
    }
}
-(void)disconnectToTcp
{
    [socketTelecom disConnect];
    [timer invalidate];
}
/**收到服务器端发送的数据*/
-(void)ReciveData:(NSDictionary*)message;
{
    if(message==NULL||[message count]==0)
        return;
    NSString *type=[message valueForKey:@"type"];
    NSString *uid=[message valueForKey:@"uid"];
    NSString *rid=[message valueForKey:@"rid"];
    if(uid!=NULL&&rid!=NULL&&type!=NULL&&[type intValue]!=PT_HEART_LINk&&[type intValue]!=PT_SETUP_LINK)
    {
        NSData *data=[self getAckMsg:type rid:rid uid:uid];
        if(data!=NULL)
            [self sendMsg:data];
    }
    //dispatch_async(dispatch_get_main_queue(), ^{
            [self handleMessage:message title:NULL isForeGround:YES];
    //});

}

/**socket连接出现错误*/
-(void)OnConnected:(BOOL)isConnected  error:(NSError *)error;
{
    if(isConnected)
    {
        NSLog(@"%@,OnConnected success.",TAG);
        //发送第一条消息
        NSData *data=[self getLinkMsg:PT_SETUP_LINK];
        if(data!=NULL)
        {
            [self sendMsg:data];
        }
        timer=[NSTimer scheduledTimerWithTimeInterval:5*60 target:self selector:@selector(socketTimeCutdown) userInfo:nil repeats:YES];
    }
    else
    {
         NSLog(@"%@,OnConnected fail.",TAG);
    }
    
}
-(void)socketTimeCutdown
{
    NSData *heartMsg=[self getLinkMsg:PT_HEART_LINk];
    if(heartMsg==NULL)
    {
        NSLog(@"%@,socketTimeCutdown,heartMsg is null.",TAG);
        return;
    }
    [self sendMsg:heartMsg];
}
-(void)sendMsg:(NSData *)msgData
{
    if(msgData==NULL)
    {
        NSLog(@"%@,sendSetUpMsg msgData is null.",TAG);
        return;
    }
    if(socketTelecom==NULL)
    {
        NSLog(@"%@,sendSetUpMsg socketTelecom is null.",TAG);
        return;
    }
    if(!socketTelecom.isConnect)
    {
        NSLog(@"%@,sendSetUpMsg socketTelecom is un connect.",TAG);
        [socketTelecom connectToHost:socketHost onPort:[socketPort intValue]];
        return;
    }
    [socketTelecom writeData:msgData];
}
-(NSData *)getLinkMsg:(PushType)type
{
    User *user=[User sharedSingleton];
    if(user==NULL||user.uid==NULL)
        return NULL;
    NSString *msg=NULL;
    if(type==PT_SETUP_LINK)
    {
       msg=[NSString stringWithFormat:@"{\"type\":%d,\"rid\":%@,\"uid\":%@,\"data\":{\"token\":\"%@\"}}",type,[Tooler getRandomCode],user.uid,self.iosToken];
    }
    else
    {
        msg=[NSString stringWithFormat:@"{\"type\":%d,\"rid\":%@,\"uid\":%@}",type,[Tooler getRandomCode],user.uid];
    }
    int length=60;//(int)msg.length+(int)kStartDataStr.length+(int)kEndDataStr.length+4;
    NSString *sendMsg=[NSString stringWithFormat:@"%@[%d]%@%@",kStartDataStr,length,msg,kEndDataStr];
    NSLog(@"%@ getLinkMsg,length is %d.",TAG,(int)sendMsg.length);
    return [sendMsg dataUsingEncoding:NSUTF8StringEncoding];
}
-(NSData *)getAckMsg:(NSString *)type rid:(NSString *)rid uid:(NSString *)uid
{
    if(type==NULL||rid==NULL||uid==NULL)
    {
        NSLog(@"%@,getAckMsg,parameters is illegale.",TAG);
        return NULL;
    }
    NSString *msg=[NSString stringWithFormat:@"{\"type\":%@,\"rid\":%@,\"uid\":%@}",type,rid,uid];
    int length=(int)msg.length+(int)kStartDataStr.length+(int)kEndDataStr.length+4;
    NSString *sendMsg=[NSString stringWithFormat:@"%@[%d]%@%@",kStartDataStr,length,msg,kEndDataStr];
    NSLog(@"%@ getAckMsg,length is %d.msg is %@",TAG,(int)sendMsg.length,sendMsg);
    return [sendMsg dataUsingEncoding:NSUTF8StringEncoding];
}

@end
